package com.qqt.csr.route.service.strategy.cs;

import com.qqt.csr.common.acl.aics.AICustomerServiceClient;
import com.qqt.csr.common.acl.aics.resp.CsMemberInfoDTO;
import com.qqt.csr.route.dto.resp.RouteResultDTO;
import com.qqt.csr.route.entity.RouteTask;
import com.qqt.csr.route.service.CsReceptionLimitService;
import com.qqt.csr.route.service.CsStatusService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 客服随机分配策略
 */
@Slf4j
@Component
public class CsRandomDistribution implements ICsDistribution {
    @Value("${csr.workbench.access.defaultLimit:0}")
    private int csWorkbenchAccessDefaultLimit;
    @Autowired
    private CsReceptionLimitService csReceptionLimitService;
    @Autowired
    private CsStatusService csStatusService;
    @Autowired
    private AICustomerServiceClient aiCustomerServiceClient;

    @Override
    public void distribution(RouteTask routeTask, RouteResultDTO resultDTO) {
        List<Long> csIdList = csStatusService.getReadyNormalCsIdList(routeTask.getSkillSet().getSkillSetId());
        List<CsMemberInfoDTO> csMemberInfoDtoList = aiCustomerServiceClient.getNormalListBy(csIdList);
        if (CollectionUtils.isEmpty(csMemberInfoDtoList)) {
            // 没有客服在线
            return;
        }

        List<CsMemberInfoDTO> onlineCsList = csMemberInfoDtoList.stream()
                .peek(m -> m.setReceptionLimit(m.getReceptionLimit() == null ? csWorkbenchAccessDefaultLimit : m.getReceptionLimit()))
                .filter(m -> m.getReceptionLimit() > 0)
                .collect(Collectors.toList());

        while (CollectionUtils.isNotEmpty(onlineCsList)){
            CsMemberInfoDTO cs = doRouteByRandom(onlineCsList);
            if (csReceptionLimitService.allocate(cs, 1)) {
                // 分配成功
                resultDTO.setCsInfo(cs);
                break;
            } else {
                onlineCsList.remove(cs);
            }
        }
    }

    private CsMemberInfoDTO doRouteByRandom(List<CsMemberInfoDTO> csList) {
        return csList.get(new Random().nextInt(csList.size()));
    }
}
